﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace AgileShare.Framework.Search.Helpers
{
    /// <summary>
    /// This class contains helper methods for working with SharePoint Search
    /// - All methods should be static
    /// - DO NOT USE SPContext
    /// </summary>
    public class SearchHelper
    {
        /// <summary>
        /// Remove Noise Words from a search string
        /// </summary>
        /// <param name="source"></param>
        /// <param name="noiseWords"></param>
        /// <returns></returns>
        public static string RemoveNoiseWords(string source, params string[] noiseWords)
        {
            return RemoveNoiseWords(source, true, false, noiseWords);
        }

        /// <summary>
        ///  Remove Noise Words from a search string
        /// </summary>
        /// <param name="source"></param>
        /// <param name="removeNonAlphaNumeric"></param>
        /// <param name="removeWhiteSpace"></param>
        /// <param name="noiseWords"></param>
        /// <returns></returns>
        public static string RemoveNoiseWords(string source, bool removeNonAlphaNumeric, bool removeWhiteSpace, params string[] noiseWords)
        {
            string retVal = source;
            if (!string.IsNullOrEmpty(retVal))
            {
                if (noiseWords != null)
                {
                    foreach (string s in noiseWords)
                    {
                        Regex regex = new Regex(string.Format(@"\b{0}\b", s), RegexOptions.IgnoreCase);
                        retVal = regex.Replace(retVal, "");
                    }
                }
                if (removeNonAlphaNumeric)
                {
                    string regExpression = @"[^a-zA-Z0-9]";
                    if (!removeWhiteSpace)
                    {
                        regExpression += @"[^a-zA-Z0-9\s]";
                    }
                    retVal = Regex.Replace(retVal, regExpression, "");
                }
            }
            return retVal;
        }

        /// <summary>
        /// Determines if a search string contains only noise words
        /// </summary>
        /// <param name="source"></param>
        /// <param name="noiseWords"></param>
        /// <returns></returns>
        public static bool ContainsOnlyNoiseWords(string source, params string[] noiseWords)
        {
            return string.IsNullOrEmpty(RemoveNoiseWords(source, true, true, noiseWords));
        }
    }
}
